package priv.wjh.study.elasticsearch.index

import co.elastic.clients.elasticsearch._types.query_dsl.QueryStringQuery
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.domain.Pageable
import org.springframework.data.elasticsearch.client.elc.NativeQuery
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder
import org.springframework.data.elasticsearch.client.elc.QueryBuilders
import org.springframework.data.elasticsearch.core.ElasticsearchOperations
import org.springframework.data.elasticsearch.core.SearchHits
import org.springframework.data.elasticsearch.core.query.Query
import priv.wjh.study.elasticsearch.ElasticsearchApplication
import spock.lang.Specification

import static org.junit.jupiter.api.Assertions.assertEquals

@SpringBootTest(classes = ElasticsearchApplication.class)
class ProductIndexRepositoryTest extends Specification {

    @Autowired
    ProductIndexRepository productIndexRepository

    @Autowired
    ElasticsearchOperations elasticsearchTemplate



    void deleteAll(){
        productIndexRepository.deleteAll();
    }


    void findByProductName() {
        given:
        ProductIndex index =new ProductIndex();
        index.setProductName("金士顿内存");
        index.setProductId(1);
        productIndexRepository.save(index);

        ProductIndex index1 =new ProductIndex();
        index1.setProductName("镁光内存");
        index1.setProductId(2);
        productIndexRepository.save(index1);

        QueryStringQuery productName = QueryBuilders.queryStringQuery("productName", "*内存*", null);
        NativeQuery query = new NativeQueryBuilder().withQuery(productName._toQuery()).build();

        SearchHits<ProductIndex> search = elasticsearchTemplate.search(query, ProductIndex.class);
        assertEquals(2, search.getTotalHits());


        Query searchQuery2 = new NativeQueryBuilder()
                .withQuery(productName._toQuery())
                .withPageable(Pageable.ofSize(1))
                .build();
        SearchHits<ProductIndex> search2 = elasticsearchTemplate.search(searchQuery2, ProductIndex.class);
        assertEquals(2, search2.getTotalHits());
        assertEquals(1, search2.getSearchHits().size());

    }
}
